#include <miscutil.h>

namespace  Util {
    std::string MiscUtil::getRandomString(std::size_t len)
    {
        /*
        note: cpp生成指定长度的随机字符串
         */
        std::string chars = "abcdefghijklmnopqrstuvwxyz"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "0123456789";
        std::random_device rd;        // 用于种子
        std::mt19937 generator(rd()); // 生成器
        std::uniform_int_distribution<> distribution(0, chars.size() - 1);

        std::string randomStr;
        for (size_t i = 0; i < len; ++i)
        {
            randomStr += chars[distribution(generator)];
        }
        return randomStr;
    }

    bool MiscUtil::getFileTree(const std::string dirname, Json::Value& root)
    {
        if (!std::filesystem::exists(dirname) || !std::filesystem::is_directory(dirname)) {
            return false;
        }
        root["name"] = dirname;
        root["type"] = "directory";
        Json::Value subFiles;
        for (auto&& it : std::filesystem::directory_iterator(dirname)) {
            if (std::filesystem::is_regular_file(it)) {
                Json::Value file;
                std::string subFileName = it.path().string();
                //std::cout << subFileName << std::endl;
                file["name"] = subFileName;
                file["type"] = "regular";
                file["file_size"] = it.file_size();
                subFiles.append(file);
            }
            else if (std::filesystem::is_directory(it)) {
                Json::Value subdir;
                getFileTree(it.path().string(), subdir);
                subFiles.append(subdir);
            }
            else {
                std::cout << "unknown file type" << std::endl;
            }
        }
        root["subfiles"] = subFiles;
        return true;
    }
    ;

}